#!/usr/bin/env python3
import os
import sys
import subprocess

# Safe Tkinter import - handles macOS library conflicts
try:
    import tkinter as tk
    from tkinter import ttk
except ImportError:
    print("PYTHON_CRASH: Tkinter Missing")
    sys.exit(1)

# NCIS v5.4 Aesthetic Palette
BG_DARK      = "#1a1a1b" 
TEXT_WHITE   = "#e0e0e0"
TEXT_DIM     = "#a0a0a0"
ACCENT_BLUE  = "#007AFF"
SUCCESS_GRN  = "#34C759"
ERROR_RED    = "#FF3B30"
BORDER_CLR   = "#404040"

class Director64Dashboard:
    def __init__(self, scan_dir):
        self.scan_dir = scan_dir
        self.root = tk.Tk()
        self.root.title("Tonys Director64")
        self.root.configure(bg=BG_DARK)
        
        # Dashboard Geometry
        ww, wh = 550, 700
        sw = self.root.winfo_screenwidth()
        sh = self.root.winfo_screenheight()
        self.root.geometry(f"{ww}x{wh}+{int(sw/2-ww/2)}+{int(sh/2-wh/2)}")
        self.root.resizable(False, False)

        self._build_ui()
        self._check_system()

    def _build_ui(self):
        # 1. Header (v5.4)
        tk.Label(self.root, text="Tonys Director64 v5.5", font=("Helvetica", 20, "bold"), 
                 bg=BG_DARK, fg=TEXT_WHITE).pack(anchor="w", padx=30, pady=(25, 10))

        # 2. Warning Box
        warn_text = ("WARNING:\nH.264 video will NOT play.\nPlease deliver movies in MPEG-4 (.mov).\n"
                        "(A Video Converter tool is available in Tools)")
        tk.Label(self.root, text=warn_text, font=("Helvetica", 12), justify="left",
                 bg=BG_DARK, fg=TEXT_WHITE).pack(anchor="w", padx=30)

        # 3. Enhanced Requirements Checklist
        req_frame = tk.Frame(self.root, bg=BG_DARK)
        req_frame.pack(fill="x", padx=30, pady=20)
        
        tk.Label(req_frame, text="System Requirements:", font=("Helvetica", 13, "bold"),
                 bg=BG_DARK, fg=TEXT_WHITE).pack(anchor="w", pady=(0, 8))

        self.stats = {}
        # Checks specified by user
        items = ["Homebrew", "Wine", "Winetricks", "FFmpeg", "QuickTime"]
        for itm in items:
            row = tk.Frame(req_frame, bg=BG_DARK)
            row.pack(fill="x", pady=2)
            tk.Label(row, text=f"• {itm}:", font=("Helvetica", 12), bg=BG_DARK, fg=TEXT_WHITE, width=12, anchor="w").pack(side="left")
            self.stats[itm] = tk.Label(row, text="Checking...", font=("Helvetica", 12, "bold"), bg=BG_DARK, fg=TEXT_DIM)
            self.stats[itm].pack(side="left")

        # 4. Integrated Director (DCR) Files List (With Refresh Button)
        list_header = tk.Frame(self.root, bg=BG_DARK)
        list_header.pack(fill="x", padx=30, pady=(5,0))

        tk.Label(list_header, text="Select DCR to Launch (Optional):", font=("Helvetica", 11, "bold"), 
                 bg=BG_DARK, fg=TEXT_DIM).pack(side="left")

        self.refresh_btn = tk.Label(list_header, text="↻ Refresh List", font=("Helvetica", 10, "bold"),
                               bg=BG_DARK, fg=ACCENT_BLUE, cursor="hand2")
        self.refresh_btn.pack(side="right")
        self.refresh_btn.bind("<Button-1>", lambda e: self._populate_list())

        list_frame = tk.Frame(self.root, bg="#2d2d2d", highlightthickness=1, highlightbackground=BORDER_CLR)
        list_frame.pack(fill="both", expand=True, padx=30, pady=(5, 10))
        
        scrollbar = tk.Scrollbar(list_frame)
        scrollbar.pack(side="right", fill="y")
        
        self.listbox = tk.Listbox(list_frame, bg="#2d2d2d", fg="white", font=("Helvetica", 13),
                                 highlightthickness=0, borderwidth=0, selectbackground=ACCENT_BLUE,
                                 yscrollcommand=scrollbar.set)
        self.listbox.pack(side="left", fill="both", expand=True)
        scrollbar.config(command=self.listbox.yview)
        
        # Populate List
        self._populate_list()
        self.listbox.bind("<Double-Button-1>", lambda e: self._finish("LAUNCH"))

    def _populate_list(self):
        self.listbox.delete(0, "end")
        self.listbox.insert("end", "  [ Launch Without DCR ]")
        files = sorted([f for f in os.listdir(self.scan_dir) if f.lower().endswith(".dcr")]) if os.path.exists(self.scan_dir) else []
        for f in files: self.listbox.insert("end", f"  ◈  {f}")
        
        # Micro-animation check: feedback that refresh happened
        orig_fg = self.refresh_btn.cget("fg")
        self.refresh_btn.config(fg=SUCCESS_GRN)
        self.root.after(500, lambda: self.refresh_btn.config(fg=orig_fg))

        # 5. Physical Button Row (Order: QUIT | TOOLS | LAUNCH)
        btn_box = tk.Frame(self.root, bg=BG_DARK, pady=25)
        btn_box.pack(fill="x", side="bottom")

        btn_opt = {"font": ("Helvetica", 12), "width": 10, "highlightbackground": BG_DARK}
        
        tk.Button(btn_box, text="Quit", command=sys.exit, **btn_opt).pack(side="left", expand=True)

        tk.Button(btn_box, text="Back", command=self.root.destroy, **btn_opt).pack(side="left", expand=True)
        
        self.tools_btn = tk.Button(btn_box, text="Tools", command=lambda: self._finish("TOOLS"), **btn_opt)
        self.tools_btn.pack(side="left", expand=True)
        
        tk.Button(btn_box, text="Launch", command=lambda: self._finish("LAUNCH"), 
                  bg=ACCENT_BLUE, fg="white", font=("Helvetica", 12, "bold"), width=14, 
                  highlightbackground=BG_DARK).pack(side="left", expand=True)

    def _check_system(self):
        def ok(cmd):
            try: return subprocess.run(cmd, shell=True, capture_output=True).returncode == 0
            except: return False
        
        wp = os.path.expanduser("~/.wine/drive_c")
        qt_ok = os.path.exists(f"{wp}/windows/system32/qtmlClient.dll") or \
                os.path.exists(f"{wp}/windows/syswow64/qtmlClient.dll") or \
                os.path.exists(f"{wp}/Program Files/QuickTime")
        
        checks = {
            "Homebrew": ok("brew --version"), "Wine": ok("wine --version"),
            "Winetricks": ok("winetricks --version"), "FFmpeg": ok("ffmpeg -version"),
            "QuickTime": qt_ok
        }
        
        any_missing = False
        for k, v in checks.items():
            self.stats[k].config(text="✅ Installed" if v else "❌ Not Installed", 
                                 fg=SUCCESS_GRN if v else ERROR_RED)
            if not v: any_missing = True
        
        if any_missing:
            self.tools_btn.config(text="Install Missing", width=14)

    def _finish(self, action):
        sel = self.listbox.curselection()
        if action == "LAUNCH":
            fpath = None
            if sel and sel[0] != 0:
                fname = self.listbox.get(sel[0]).split("◈")[-1].strip()
                fpath = os.path.join(self.scan_dir, fname)
            
            # Signal the shell launcher via signal file for non-blocking persistence
            signal_file = "/tmp/director_launch_signal"
            if fpath:
                with open(signal_file, "w") as f: f.write(fpath)
            else:
                with open(signal_file, "w") as f: f.write("LAUNCH_DEFAULT")
            
            # To keep it open as requested, we DON'T destroy()
            self.root.title("Director64 • Launching...")
            self.root.after(2000, lambda: self.root.title("Tonys Director64"))
            
        else:
            act = "INSTALL_MISSING" if self.tools_btn.cget("text") == "Install Missing" else "TOOLS"
            print(f"ACTION:{act}")
            # Dashboard tools usually exit to run the tool
            self.root.destroy()

if __name__ == "__main__":
    # Corrected argument indexing:
    # 1st arg: scan_path
    # 2nd arg: any flags (optional)
    scan_p = os.getcwd()
    if len(sys.argv) > 1:
        # If the first arg is a flag, skip it, otherwise it's the path
        if sys.argv[1].startswith("-"):
            if len(sys.argv) > 2: scan_p = sys.argv[2]
        else:
            scan_p = sys.argv[1]
            
    try:
        Director64Dashboard(scan_p).root.mainloop()
    except Exception as e:
        with open("/tmp/director64_python_error.log", "w") as f:
            import traceback
            traceback.print_exc(file=f)
        sys.exit(1)
